<?php

namespace app\api\controller;
use app\api\model\RoleRule as RoleRuleModel;
use app\api\model\Rule as RuleModel;
use app\Request;
class RoleRule
{
    public function index(Request $request)
    {
        //规则信息
        $db = new RuleModel();
        $list = $db->where('status',1)->field('id,name,pid,url,img')->select();
        return json(['code' => 200, 'msg' => '查询权限成功', 'data' => $list]);
    }



    public function save(Request $request)
    {
        //角色id 和 分配的角色id信息
        if (!$request->isPost()) {
            return json(['code' => 500, 'msg' => '请求方式错误']);
        }
        $role_id = $request->param('role_id');
        $rule_id = $request->param('rule_id');
        $db = new RoleRuleModel();
        $info = $db->where('role_id', $role_id)->find();
        if ($info) {
            // 准备更新的数据
            $updateData = [
                'rule_id' => $rule_id,  // 更新 rule_id 字段为 $rule_id 的值
            ];
            // 执行更新操作
            $res = $db->where('id', $info['id'])->update($updateData);
        }else{
            $data['role_id'] = $role_id;
            $data['rule_id'] = $rule_id;
            $res = $db->save($data);
        }
        if ($res) {
            return json(['code' => 200, 'msg' => '操作成功']);
        }else {
            return json(['code' => 500, 'msg' => '操作失败']);
        }
    }




    public function read(Request $request)
    {
        if (!$request->isPost()) {
            return json(['code' => 500, 'msg' => '请求方式错误']);
        }
        $admin_id = $request->param('admin_id');

        $db = new AdminRoleModel();
        $info = $db->where('admin_id', $admin_id)->find();
        $db = new RoleModel();
        $list = $db->where('status', 1)->field('id,name')->select()->toArray();
        if ($info) {

            $tmp = explode(',', $info['role_id']);

           foreach ($list as $k => $v) {

               if (in_array($v['id'], $tmp)) {
                   $list[$k]['check'] = true;
               } else {
                   $list[$k]['check'] = false;
               }
           }
        }else{
            foreach ($list as $k => $v) {
                $list[$k]['check'] = false;
            }
        }
        return json(['code' => 200, 'msg' => '获取角色成功', 'data' => $list]);
    }











}